//
//  WZLReadViewController.m
//  MapleLeaf
//
//  Created by WangZe on 15/12/2.
//  Copyright © 2015年 AntennaBabyTeam. All rights reserved.
//

#import "WZLReadViewController.h"
#import "WZLReadCollectionViewCell.h"
#import "ZGSReadModel.h"
#import "WZLReadCollectionViewCell.h"
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
@interface WZLReadViewController ()<UIScrollViewDelegate, UICollectionViewDataSource, UICollectionViewDelegate, UIGestureRecognizerDelegate, BaseReadImageViewDelegate, UIAlertViewDelegate, UIActionSheetDelegate>
//@property(nonatomic, strong)UIScrollView *myScrollView;
@property(nonatomic, strong)NSMutableArray *dataArr;
@property(nonatomic, strong)UICollectionView *collectionView;
@property(nonatomic, strong)UIView *topView;
@property(nonatomic, strong)UILabel *nameLabel;
@property(nonatomic, strong)UIView *downView;
@property(nonatomic, strong)UIActionSheet *actionSheet;
@property(nonatomic, strong)UIImageView *hehe;
@end

@implementation WZLReadViewController
- (void)loadView
{
    [super loadView];
}
- (void)viewDidLoad {
    [super viewDidLoad];
//最强小组 王泽龙
    // Do any additional setup after loading the view.
//    self.myScrollView.hidden = NO;
    self.view.backgroundColor = [UIColor blackColor];
    self.collectionView.hidden = NO;
    
//    [self createTopView];
//    [self createDownView];
    
    
    if (self.zipArr.count == 0) {
        
        [self createData];
    }
    
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    NSLog(@"~~~~~~~~~~~~~~~~~~~~~~~%@", self.readArr);
}


- (void)longPressAction:(UILongPressGestureRecognizer *)longPress
{
    
    UIImageView *imageView = (UIImageView *)longPress.view;
    self.hehe = imageView;
    self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"提示" delegate:self cancelButtonTitle:@"返回" destructiveButtonTitle:nil otherButtonTitles:@"保存图片", nil];
    _actionSheet.actionSheetStyle = UIActionSheetStyleBlackOpaque;
    [_actionSheet showInView:self.view];
    [self.actionSheet resignFirstResponder];
    
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 0) {
        [self savePic:self.hehe.image];
    }
    [self.actionSheet resignFirstResponder];
}
- (void)savePic:(UIImage *)image;
{
    ALAssetsLibrary *library = [[ALAssetsLibrary alloc]init];
    [library writeImageToSavedPhotosAlbum:image.CGImage orientation:(ALAssetOrientation) image.imageOrientation completionBlock:^(NSURL *asSetUrl,NSError *error){
        if (error) {
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"存储失败"
                                                           message:nil
                                                          delegate:nil
                                                 cancelButtonTitle:@"确定"
                                                 otherButtonTitles:nil, nil];
            [alert show];
        }else{
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"存储成功"
                                                           message:nil
                                                          delegate:nil
                                                 cancelButtonTitle:@"确定"
                                                 otherButtonTitles:nil, nil];
            [alert show];
            
        }
    }];
    [self.actionSheet resignFirstResponder];
}

- (void)createData
{
    [BaseAFN GETURLByString:[NSString stringWithFormat:@"%@/config.json", self.model.onlineUrl] AFNData:^(id result) {
        NSLog(@"%@", result);
        self.dataArr = nil;
        self.dataArr = [NSMutableArray arrayWithArray:result];
        if (self.dataArr.count) {
            
            
            [self.dataArr insertObject:[self.dataArr lastObject] atIndex:0];
            [self.dataArr addObject:self.dataArr[1]];

        }
        self.collectionView.contentSize = CGSizeMake(self.dataArr.count * WIDTH, 0);
        
        [self.collectionView setContentOffset:CGPointMake(WIDTH, 0) animated:NO];
//        self.collectionView.contentOffset = CGPointMake(WIDTH, 0);
        self.collectionView.backgroundColor = [UIColor whiteColor];
        
        
        [self.collectionView reloadData];
    }];
}
- (void)createOtherData
{
    [BaseAFN GETURLByString:[NSString stringWithFormat:@"%@/config.json", self.model.onlineUrl] AFNData:^(id result) {
        NSLog(@"%@", result);
        self.dataArr = nil;
        self.dataArr = [NSMutableArray arrayWithArray:result];
        if (self.dataArr.count) {
            
            [self.dataArr insertObject:[self.dataArr lastObject] atIndex:0];
            [self.dataArr addObject:self.dataArr[1]];
            
        }
        self.collectionView.contentSize = CGSizeMake(self.dataArr.count * WIDTH, 0);
        
        [self.collectionView setContentOffset:CGPointMake(WIDTH * (self.dataArr.count - 2), 0) animated:NO];

        [self.collectionView reloadData];
    }];
}
- (void)setNumOfCartoon:(NSInteger)numOfCartoon
{
    if (_numOfCartoon != numOfCartoon) {
        _numOfCartoon = numOfCartoon;
    }
    self.title = [NSString stringWithFormat:@"第%ld话", self.numOfCartoon + 1];
//    self.nameLabel.text = [NSString stringWithFormat:@"第%ld话", self.numOfCartoon + 1];
}

- (void)viewWillAppear:(BOOL)animated
{
    self.navigationController.navigationBarHidden = NO;
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.backgroundColor = [UIColor clearColor];
    self.navigationController.navigationBar.hidden = NO;
    self.navigationController.hidesBottomBarWhenPushed = YES;
}

- (UICollectionView *)collectionView
{
    if (!_collectionView) {
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
        flowLayout.itemSize = CGSizeMake(WIDTH, HEIGHT);
        flowLayout.minimumInteritemSpacing = 0;
        flowLayout.minimumLineSpacing = 0;
        flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        self.collectionView = [[UICollectionView alloc] initWithFrame:self.view.frame collectionViewLayout:flowLayout];
        
        [self.view addSubview:self.collectionView];
        [_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
            Left(self.view.mas_left, 0);
            Right(self.view.mas_right, 0);
            Top(self.view.mas_top, 0);
            Bottom(self.view.mas_bottom, 0);
        }];
        [self.collectionView setDelegate:self];
        [self.collectionView setDataSource:self];
        self.collectionView.pagingEnabled= YES;
        [self.collectionView registerClass:[WZLReadCollectionViewCell class] forCellWithReuseIdentifier:@"read"];
        
        
    }
    return _collectionView;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (self.dataArr.count != 0) {
        
        return self.dataArr.count;
    }
    if (self.zipArr.count != 0) {
        return self.zipArr.count;
    }
    return 10;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    WZLReadCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"read" forIndexPath:indexPath];
    if (self.zipArr.count == 0)
    {
        NSString * Str =  [NSString stringWithFormat:@"%@/%@", self.model.onlineUrl, self.dataArr[indexPath.row]];
        if (indexPath.row == 0) {
            cell.picImageView.backgroundColor = [UIColor blackColor];
        }
        else if (indexPath.row == self.dataArr.count - 1)
        {
            cell.picImageView.backgroundColor = [UIColor blackColor];
        }
        else{
            cell.str = Str;
            
            cell.picImageView.tag = 1000 + indexPath.item;
            cell.picImageView.userInteractionEnabled = YES;
            cell.picImageView.multipleTouchEnabled = YES;
            cell.tag = 1000;
            [cell.picImageView becomeFirstResponder];
            cell.picImageView.delegate = self;
            UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
            [cell.picImageView addGestureRecognizer:longPress];
            
        }
    }
    else
    {
        NSString *str =  [NSString stringWithFormat:@"%@/%@", self.zipStr, self.zipArr[indexPath.row]];
        
        cell.str = str;
        cell.picImageView.tag = 1000 + indexPath.item;
        cell.picImageView.userInteractionEnabled = YES;
        cell.picImageView.multipleTouchEnabled = YES;
        cell.tag = 1000;
        [cell.picImageView becomeFirstResponder];
        cell.picImageView.delegate = self;
        UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPressAction:)];
        [cell.picImageView addGestureRecognizer:longPress];
        
       
    }
    return cell;
}



- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    if (self.dataArr.count != 0) {
    if (scrollView == self.collectionView) {
        if (scrollView.contentOffset.x == (UIAccelerationValue)(self.dataArr.count - 1) *WIDTH) {
            
            self.numOfCartoon++;
            if (self.numOfCartoon > self.readArr.count - 1) {
                self.numOfCartoon = 0;
            }
            self.model = self.readArr[self.numOfCartoon];
            [self createData];
        }
        
        if (scrollView.contentOffset.x == (UIAccelerationValue)(0 * WIDTH)) {
            if (self.numOfCartoon == 0) {
                self.numOfCartoon = self.readArr.count - 1;
            }
            else{
                
                self.numOfCartoon--;
            }
            self.model = self.readArr[self.numOfCartoon];
            [self createOtherData];
        }
    }
    }
}
- (void)TouchsBegintouchPointX:(NSInteger)x WithTouchPointY:(NSInteger)y
{
    NSLog(@"touch (x, y) is (%ld, %ld)", x, y);
    if (x > WIDTH / 3 * 2) {
        NSLog(@"%f", self.collectionView.contentOffset.x);
        self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x + WIDTH, 0);
        if (self.collectionView.contentOffset.x == (UIAccelerationValue)(self.dataArr.count - 1) *WIDTH) {
            
            self.numOfCartoon++;
            if (self.numOfCartoon > self.readArr.count - 1) {
                self.numOfCartoon = 0;
            }
            self.model = self.readArr[self.numOfCartoon];
            [self createData];
        }
    }
    else if (x < WIDTH / 3)
    {
        self.collectionView.contentOffset = CGPointMake(self.collectionView.contentOffset.x - WIDTH, 0);
        if (self.collectionView.contentOffset.x == (UIAccelerationValue)(0 * WIDTH)) {
            if (self.numOfCartoon == 0) {
                self.numOfCartoon = self.readArr.count - 1;
            }
            else{
                
                self.numOfCartoon--;
            }
            self.model = self.readArr[self.numOfCartoon];
            [self createOtherData];
        }
    }
    else
    {
        self.topView.hidden = NO;
        self.downView.hidden = NO;
    }
 
}

- (void)createTopView
{
    self.topView = [[UIView alloc] init];
    [self.view addSubview:self.topView];
    self.topView.backgroundColor = [UIColor grayColor];
    self.topView.alpha = 0.4;
    [self.topView mas_makeConstraints:^(MASConstraintMaker *make) {
        Left(self.view.mas_left, 0);
        Right(self.view.mas_right, 0);
        Top(self.view.mas_top, 0);
        HequalNum(50);
    }];
    self.topView.hidden = YES;
    
    UIButton *returnButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [self.topView addSubview:returnButton];
    [returnButton mas_makeConstraints:^(MASConstraintMaker *make) {
        Left(self.topView.mas_left, 10);
        Top(self.topView.mas_top, 10);
        Bottom(self.topView.mas_bottom, -10);
        WequalNum(40);
    }];
    [returnButton addTarget:self action:@selector(returnButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [returnButton setTitle:@"返回" forState:UIControlStateNormal];
    
    self.nameLabel = [[UILabel alloc] init];
    [self.topView addSubview:self.nameLabel];
    [self.nameLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        CenterX(self.topView.mas_centerX);
        Top(self.topView.mas_top, 10);
        Bottom(self.topView.mas_bottom, -10);
        WequalNum(100);
    }];
    self.nameLabel.textColor = [UIColor redColor];
    self.nameLabel.textAlignment = NSTextAlignmentCenter;
    self.nameLabel.text = [NSString stringWithFormat:@"第%ld话", self.numOfCartoon + 1];
    
    
}
- (void)returnButtonAction:(UIButton *)button
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
- (void)createDownView
{
    self.downView = [[UIView alloc] init];
    [self.view addSubview:self.downView];
    self.downView.backgroundColor = [UIColor grayColor];
    self.downView.alpha = 0.4;
    [self.downView mas_makeConstraints:^(MASConstraintMaker *make) {
        Left(self.view.mas_left, 0);
        Right(self.view.mas_right, 0);
        Bottom(self.view.mas_bottom, 0);
        HequalNum(50);
    }];
    self.downView.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
